package com.backupdeppeseek;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class FileQrConverter {

    public static void fileToQr(String filePath, String qrPath) throws Exception {
        // 读取文件内容
        String content = new String(Files.readAllBytes(Paths.get(filePath)), "UTF-8");

        // Base64 编码
        String encodedContent = Base64.getEncoder().encodeToString(content.getBytes());

        // 生成二维码
        BitMatrix bitMatrix = new MultiFormatWriter().encode(encodedContent, BarcodeFormat.QR_CODE, 300, 300);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", Paths.get(qrPath));
        System.out.println("二维码已保存至 " + qrPath);
    }

    public static void qrToFile(String qrPath, String outputFile) throws Exception {
        // 读取二维码图片
        BufferedImage bufferedImage = ImageIO.read(new File(qrPath));
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

        // 解码二维码
        Result result = new MultiFormatReader().decode(binaryBitmap);
        String decodedContent = new String(Base64.getDecoder().decode(result.getText()));

        // 将解码内容写入文件
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile))) {
            writer.write(decodedContent);
        }
        System.out.println("文件已恢复至 " + outputFile);
    }

    public static void main(String[] args) throws Exception {
        String inputFile = "src/main/resources/example.txt";
        String qrCodeImage = "src/main/resources/output_qr.png";
        String restoredFile = "src/main/resources/restored.txt";

        fileToQr(inputFile, qrCodeImage);
        qrToFile(qrCodeImage, restoredFile);
    }
}